<template>
    <div class="pagestyle">
        <list_controller v-show="state.options.tabName ==1" ref="zujianname" :options="state.options" pageName="区域信息">
            <template v-slot:opraCurdBtnAll>
                <el-button class="btn" type="primary" link @click="addBtn('mul')">
                    <el-icon style="margin-right: 2px;">
                        <svg-icon class-name="search-icon" icon-class="addtotal" />
                    </el-icon>新增
                </el-button>
                <el-button class="btn" type="primary" link @click="deleteBtn('mul')">
                    <el-icon>
                        <DeleteFilled />
                    </el-icon>删除
                </el-button>
            </template>
            <template v-slot:selectName1>
                <el-select class="sel" v-model="state.options.tabName" size="small" style="width: 60px"
                    @change="tabChangeSel">
                    <el-option v-for="item in state.options.tabList" :key="item.tabIndex" :label="item.name"
                        :value="item.tabIndex" />
                </el-select>
            </template>
            <template v-slot:opraCurdBtn1="row">
                <span>
                    <el-button type="primary" link size="small" @click="lookBtn(row.row.row)">查看</el-button>
                    <el-button type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
                    <el-button type="primary" link size="small" @click="deleteBtn(row.row.row)">删除</el-button>
                </span>
            </template>
        </list_controller>
        <!-- 新增弹框 -->
        <teleport to="body">
            <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto"
                v-model="state.addModal" resize :mask="true">
                <template #title>
                    <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
                </template>
                <template #default>
                    <div class="form_box">
                        <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="区域名称" prop="areaName">
                                        <el-input clearable v-model="state.formData.areaName" placeholder="请输入">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="区域类型" prop="areaTypeName">
                                        <el-select clearable filterable v-model="state.formData.areaTypeName"
                                            placeholder="请选择" allow-create>
                                            <el-option v-for="item in state.searchAllList" :key="item.id"
                                                :label="item.areaTypeName" :value="item.areaTypeName">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="所属区域" prop="parentAreaId">
                                        <el-tree-select v-model="state.formData.parentAreaId" ref="treeRef"
                                            :data="state.searchTreeList" node-key="id" clearable
                                            :default-expanded-keys="[state.formData.parentAreaId]"
                                            :props="{  children: 'childList',value: 'id', label: 'areaName'}"
                                            placeholder="请选择" highlight-current @node-click="nodeclick"
                                            check-strictly />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <p class="mask_sub_title fbc">
                                        <span>坐标集合<el-button size="small" link type="primary">GIS获取</el-button> </span>
                                        <el-col :span="1">
                                            <svg-icon class-name="search-icon" icon-class="addblue"
                                                @click="addblueClick(index)" />
                                        </el-col>
                                    </p>
                                </el-col>
                                <el-row :gutter="20" style="padding:0 10px;display:flex;align-items:center;"
                                    v-for="(item,index) in state.locations" :key="index">
                                    <el-col :span="7">
                                        <el-form-item label="X">
                                            <el-input clearable v-model="item.locationX" placeholder="请输入"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item label="Y">
                                            <el-input clearable v-model="item.locationY" placeholder="请输入"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item label="Z">
                                            <el-input clearable v-model="item.locationZ" placeholder="请输入"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="1">
                                        <svg-icon class-name="search-icon" icon-class="delred"
                                            @click="delredClick(index)" />
                                    </el-col>
                                </el-row>
                            </el-row>
                        </el-form>
                        <div class="form_footer">
                            <el-button @click="cancel">取消</el-button>
                            <el-button type="primary" @click="submitForm">
                                确定
                            </el-button>
                        </div>
                    </div>
                </template>
            </vxe-modal>
        </teleport>
        <!-- 详情 -->
        <el-drawer v-model="state.drawerShow" direction="rtl" size="50%" close-on-click-modal :modal="true">
            <template #header="{ close, titleId, titleClass }">
                <h4 class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="dot" /><span>区域信息详情</span></h4>
            </template>
            <p class="drawer_sub_title">
                <span class="sub_title_line">基础信息</span>
            </p>
            <el-row :gutter="20"
                style="background: rgba(91, 109, 128, 0.04);display: flex;align-items: center;padding: 20px 0;">
                <el-col :span="8" style="text-align: center;">
                    <div class="img_box">
                        <span>{{ state.formData.areaName }}</span>
                    </div>
                </el-col>
                <el-col :span="16">
                    <el-row :gutter="20">
                        <el-col :span="7">
                            <p>区域类型</p>
                            <p>{{state.formData.areaTypeName}}</p>
                        </el-col>
                        <el-col :span="9">
                            <p>地理位置</p>
                            <el-button link type="primary" v-for="item in state.formData.locations">
                                {{item.locationX}},{{item.locationY}},{{item.locationZ}}</el-button>
                        </el-col>
                        <el-col :span="8">
                            <p>上级区域</p>
                            <p>{{state.formData.parentAreaName}}</p>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top:10px;">
                <el-col :span="8">
                    <p class="drawer_sub_title">
                        <span class="sub_title_line">区域下分站</span>
                    </p>
                    <vxe-table height="240" :data="state.searchChildStationList">
                        <vxe-column title="序号" type="seq" :width="55"></vxe-column>
                        <vxe-column title="分站编号" field="stationCode">
                        </vxe-column>
                        <vxe-column title="安装地点" field="stationPlaceName">
                        </vxe-column>
                    </vxe-table>
                </el-col>
                <el-col :span="8">
                    <p class="drawer_sub_title">
                        <span class="sub_title_line">下级区域</span>
                    </p>
                    <vxe-table height="240" :data="state.searchChildAreaUrlList">
                        <vxe-column title="序号" type="seq" :width="55"></vxe-column>
                        <vxe-column title="区域名称" field="areaName">
                        </vxe-column>
                    </vxe-table>
                </el-col>
                <el-col :span="8">
                    <p class="drawer_sub_title fbc">
                        <span class="sub_title_line">相邻区域</span>
                        <el-button link type="primary" @click="nearAreaeditclick">编辑</el-button>
                    </p>
                    <vxe-table height="240" :data="state.nearAreaList">
                        <vxe-column type="seq" title="序号" width="55"></vxe-column>
                        <vxe-column title="区域名称" field="nearAreaName">
                        </vxe-column>
                    </vxe-table>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <p class="drawer_sub_title">
                        <span class="sub_title_line">人员信息</span>
                    </p>
                    <list_controller ref="zujianname" :options="state.options1" pageName="" @deleteBtn="deleteBtn"
                        @addBtn="addBtn" @editBtn="editBtn" @lookBtn="lookBtn" :addBtnMul="false" :delBtnMul="false"
                        :editBtnMul="false"></list_controller>
                </el-col>
            </el-row>
        </el-drawer>
        <!-- 相邻区域编辑 -->
        <el-drawer v-model="state.drawerNearShow" direction="rtl" size="40%" close-on-click-modal :modal="true" :before-close="handleClose">
            <template #header="{ close, titleId, titleClass }">
                <h4 class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="dot" /><span>相邻区域设置</span></h4>
            </template>
            <el-radio-group v-model="state.nearAreatabName" size="small" @change="tabChange">
                <el-radio-button v-for="item in state.nearAreaListTab" :label="item.name" :value="item.tabIndex" />
            </el-radio-group>
            <div>
                <p style="display:flex;justify-content:flex-end;" v-if="state.nearAreatabName == '未设置相邻'">
                    <el-button link type="primary" size="mini" @click="settingnearClick(1,'mul')">
                        <svg-icon class-name="search-icon" icon-class="setting" />设置单向相邻
                    </el-button>
                    <el-button link type="primary" style="margin-left:10px;" size="mini"
                        @click="settingnearClick(2,'mul')">
                        <svg-icon class-name="search-icon" icon-class="setting" />设置双向相邻
                    </el-button>
                </p>
                <p v-else style="display:flex;justify-content:flex-end;">
                    <el-button link type="primary" style="margin-left:10px;" size="mini"
                        @click="settingnearClick(undefined,'mul')">
                        <svg-icon class-name="search-icon" icon-class="setting" />取消相邻
                    </el-button>
                </p>
                <vxe-table height="240" :data="state.nearinfoAreaList" @checkbox-change="checkchange"
                    v-if="state.nearAreatabName == '未设置相邻'">
                    <vxe-column type="checkbox" :width="42"></vxe-column>
                    <vxe-column title="编号" type="seq" :width="55"></vxe-column>
                    <vxe-column title="区域名称" field="areaName">
                    </vxe-column>
                    <vxe-column title="操作" field="show">
                        <template #default="{row}">
                            <p>
                                <el-button link type="primary" size="mini" @click="settingnearClick(1,row)">
                                    设置单向相邻
                                </el-button>
                                <el-button link type="primary" style="margin-left:10px;" size="mini"
                                    @click="settingnearClick(2,row)">
                                    设置双向相邻
                                </el-button>
                            </p>
                        </template>
                    </vxe-column>
                </vxe-table>
                <vxe-table height="240" :data="state.nearAreaList" @checkbox-change="checkchange" v-else>
                    <vxe-column type="checkbox" :width="42"></vxe-column>
                    <vxe-column title="编号" type="seq" :width="55"></vxe-column>
                    <vxe-column title="区域名称" field="nearAreaName">
                    </vxe-column>
                    <vxe-column title="操作" field="show">
                        <template #default="{row}">
                            <el-button link type="primary" style="margin-left:10px;" size="mini"
                                @click="settingnearClick(undefined,row)">
                                取消相邻
                            </el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
        </el-drawer>
        <!-- 四维导图 -->
        <div class="fbc" style="padding:25px 20px 0 20px;font-weight: 700;">
            <div class="ffc">
                <span>区域信息</span>
                <el-select class="sel" v-model="state.options.tabName" size="small" style="width: 60px"
                    @change="tabChangeSel">
                    <el-option v-for="item in state.options.tabList" :key="item.tabIndex" :label="item.name"
                        :value="item.tabIndex" />
                </el-select>
            </div>
            <el-button type="primary" link @click="daotuAddClick">
                <svg-icon class-name="search-icon" icon-class="addtotal" />新增区域</el-button>
        </div>
        <div v-show="state.options.tabName == 2" style="width: 100%; height: 100%;padding-bottom:50px;"
            ref="jsmindContainer"></div>
    </div>
</template>
<script setup>
    import {
        ref,
        onMounted,
        nextTick,
        computed,
        reactive,
        inject,
        h
    } from "vue";
    import "jsmind/style/jsmind.css";
    import JsMind from "jsmind";
    import
    CreateDom
    from '@/utils/daotu.js'
    import list_controller from "@/components/commonCom/list_controller";
    import {
        table_headers
    } from '@/components/commonCom/table_headers';
    import axios from "@/utils/request"
    import usePagesStore from '@/store/modules/pages'
    import {
        gettypeList,
        getsearchTree
    } from '@/api/config'
    const {
        proxy
    } = getCurrentInstance();
    const store = usePagesStore()
    components: {
        list_controller
    }
    const treeRef = ref(null)
    const resultData = ref({})
    const filtername = ref([])
    const filtername1 = ref([])
    const jsmindContainer = ref(null)
    const resultDatatree = ref([])
    let jm = null
    const state = reactive({
        isHighLightid: undefined,
        fromtree: false,
        jsmindList: [],
        nearrecords: [],
        options: {
            tabName: 2,
            tabList: [{
                tabIndex: 1,
                name: '列表'
            }, {
                tabIndex: 2,
                name: '多维'
            }],
            tableheads: computed(() => table_headers.areaBasic),
            queryList: {
                dropdownUrl: '',
                querys: [],
                queryMap: new Map([
                    ['sensorTypeId', 'safety_pointType'],
                    ['deviceTypeId', 'safety_deviceType'],
                    ['alarmTypeId', 'alarmType']
                ])
            },
            dataUrl: '/area/info/searchAll',
            delUrl: '/area/info/deleteArea',
            addUrl: '/area/info/addArea',
            descUrl: '/area/info/searchAreaDetail',
            editUrl: '/area/info/editArea',
        },
        // 表单
        addModal: false,
        modalTitle: '新增地理位置',
        drawerShow: false,
        formRef: null,
        formData: {
            parentAreaId: ''
        },
        rules: {
            areaName: [{
                required: true,
                message: '请输入区域名称',
                trigger: 'blur'
            }],
            areaTypeName: [{
                required: true,
                message: '请选择区域类型',
                trigger: 'change'
            }]
        },
        editId: undefined,
        searchAllList: [],
        searchTreeList: [],
        locations: [{
            locationX: undefined,
            locationY: undefined,
            locationZ: undefined
        }],
        nearAreaUrl: '/area/near/search/',
        nearinfoAreaList: [], //非相邻
        nearAreaList: [], //相邻
        nearAreatabName: '未设置相邻',
        nearAreaListTab: [{
            name: '未设置相邻',
            tabIndex: 1
        }, {
            name: '已设置相邻',
            tabIndex: 1
        }],
        nearId: undefined,
        drawerNearShow: false,
        searchChildAreaUrl: '/area/info/searchChildArea/',
        settingAreaUrl: '/area/near/add',
        searchChildAreaUrlList: [],
        searchChildAreaUrlTab: [],
        searchChildStationList: [],
        options1: {
            tabList: [{
                tabIndex: 1,
                name: '列表'
            }, {
                tabIndex: 2,
                name: '多维'
            }],
            tableheads: computed(() => table_headers.areaBasic),
            queryList: {
                dropdownUrl: '',
                querys: [{
                    field: 'stationTypeName',
                    title: '姓名',
                    type: 'input',
                    binddata: ''
                }, {
                    field: '职位',
                    title: '分站模式',
                    type: 'select',
                    binddata: '',
                    options: [],
                }],
                queryMap: new Map([
                    ['sensorTypeId', 'safety_pointType'],
                    ['deviceTypeId', 'safety_deviceType'],
                    ['alarmTypeId', 'alarmType']
                ])
            },
            dataUrl: '/area/info/searchAll',
            delUrl: '/area/info/deleteArea',
            addUrl: '/area/info/addArea',
            descUrl: '/area/info/searchDetail',
            editUrl: '/area/info/editArea',
        }
    })
    // 最后在需要使用的页面中调用这个方法myFn() 
    // 比如可以放在点击事件中
    const myFn = inject("reload");
    // 查看按钮
    function lookBtn(row) {
        state.drawerShow = true
        state.nearId = row.id
        getChildAreaList()
        getnearAreaList1('已设置相邻')
        getsearchChildStation()
        axios.post(state.options.descUrl, {
            id: row.id
        }).then(res => {
            if (res.code == 200) {
                state.formData = res.data
            }
        })
    }
    // 列表-新增按钮
    function addBtn(row) {
        state.modalTitle = '新增区域'
        state.addModal = true
        state.fromtree = false
        state.formData = {}
        state.locations = [{
            locationX: 0,
            locationY: 0,
            locationZ: 0
        }]
        state.formData.parentAreaId = null
        state.editId = undefined
        getSelList()
    }
    // 获取父级id
    function findParentArr(targetId, mock) {
        const ids = []

        function getParent(sources) {
            if (Array.isArray(sources)) {
                return sources.find(elm => {
                    let rs = getParent(elm)
                    if (rs) {
                        ids.push(elm.id)
                    }
                    return rs
                })
            }
            if (sources.id === targetId) {
                return true
            }
            if (Array.isArray(sources.childList)) {
                return getParent(sources.childList)
            }
        }
        getParent(mock)
        return ids
    }

    // 获取下拉选
    function getSelList() {
        gettypeList().then(res => {
            state.searchAllList = res.data
        })
        getsearchTree().then(res => {
            state.searchTreeList = res.data
        })
    }
    getSelList()
    // 列表-编辑按钮
    function editBtn(row) {
        state.modalTitle = '编辑区域'
        state.addModal = true
        state.fromtree = false
        axios.post(state.options.descUrl, {
            id: row.id
        }).then(res => {
            if (res.code == 200) {
                state.formData = res.data
                state.locations = res.data.locations
                // state.formData.areaTypeId = Number(state.formData.areaTypeId)
                if (state.formData.parentAreaId == 0) {
                    state.formData.parentAreaId = null
                } else {
                    let arr = findParentArr(state.formData.parentAreaId, state.searchTreeList)
                    filtername.value = arr
                }
                state.editId = res.data.id
            }
        })
    }
    // 列表-删除按钮
    function deleteBtn(row) {
        let ids = []
        if (row != 'mul') {
            ids = [row.id]
        } else {
            if (store.records.length > 0) {
                ids = store.records.map(item => {
                    return item.id
                })
            } else {
                proxy.$modal.msgSuccess('请先勾选所要删除数据!');
            }
        }
        if (ids.length > 0) {
            axios.post(state.options.delUrl, ids).then(res => {
                if (res.code == 200) {
                    proxy.$refs['zujianname'].getData()
                    state.addModal = false
                    proxy.$modal.msgSuccess(res.msg);
                    store.records = []
                }
            })
        }

    }
    /** 列表-提交按钮 */
    function submitForm() {
        proxy.$refs["formRef"].validate(valid => {
            if (valid) {
                if (filtername1.value.length > 0) {
                    state.formData.rootId = filtername1.value[1]
                } else {
                    state.formData.rootId = null
                }
                if (filtername.value.length > 0) {
                    state.formData.rootId = filtername.value[0]
                    if (filtername.value[0] == 'root') {
                        state.formData.rootId = null
                    } else {
                        state.formData.rootId = filtername.value[0]
                    }
                } else {
                    state.formData.rootId = null
                }
                if (state.formData.parentAreaId == '') {
                    state.formData.parentAreaId = null
                    state.formData.rootId = null
                }
                if (state.editId) {
                    state.formData.id = state.editId
                    axios.post(state.options.editUrl, state.formData).then(res => {
                        if (res.code == 200) {
                            proxy.$refs['zujianname'].getData()
                            state.addModal = false
                            proxy.$modal.msgSuccess(res.msg);
                            filtername1.value = []
                            filtername.value = []
                            state.formData.rootId = undefined
                            getSelList()
                            if (state.fromtree) {
                                myFn()
                            }
                        }
                    })
                } else {
                    // if (filtername1.value.length > 0) {
                    //     state.formData.rootId = filtername1.value[1]
                    // }
                    state.formData.locations = state.locations
                    axios.post(state.options.addUrl, state.formData).then(res => {
                        if (res.code == 200) {
                            proxy.$refs['zujianname'].getData()
                            state.addModal = false
                            proxy.$modal.msgSuccess(res.msg);
                            filtername1.value = []
                            filtername.value = []
                            state.formData.rootId = undefined
                            getSelList()
                            if (state.fromtree) {
                                myFn()
                            }
                        }
                    })
                }
            }
        })
    }

    function cancel() {
        state.addModal = false
    }

    // 获取编辑详情表格数据-下级区域
    function getChildAreaList() {
        axios.post(state.searchChildAreaUrl + state.nearId, {}).then(res => {
            if (res.code == 200) {
                state.searchChildAreaUrlList = res.data
            }
        })
    }
    // 获取详情-区域下分站
    function getsearchChildStation() {
        axios.post('/area/info/searchChildStation/' + state.nearId, {}).then(res => {
            state.searchChildStationList = res.data
        })
    }
    // 获取相邻非相邻
    function getnearAreaList1(val) {
        if (val == '未设置相邻') {
            axios.post('/area/info/search/' + state.nearId, {}).then(res => {
                if (res.code == 200) {
                    state.nearinfoAreaList = res.data
                }
            })
        } else {
            axios.post(state.nearAreaUrl + state.nearId, {}).then(res => {
                if (res.code == 200) {
                    state.nearAreaList = res.data
                }
            })
        }
    }
    // 编辑相邻区域
    function nearAreaeditclick() {
        state.drawerNearShow = true
        getnearAreaList1('未设置相邻')
    }
    // 点击事件-坐标集合-删除
    function delredClick(index) {
        state.locations.splice(index, 1);
    }
    // 坐标集合-新增
    function addblueClick(index) {
        state.locations.push({
            locationX: 0,
            locationY: 0,
            locationZ: 0
        })
        getSelList()
    }
    // 所属区域点击事件
    function nodeclick(data, node) {
        recursionFun(node)
    }
    // 递归函数
    const recursionFun = (node) => {
        let arr = []
        if (!node.parent) {
            return
        }
        arr.unshift(node.data.id)
        filtername.value = arr
        recursionFun(node.parent)
    }
    // 设置相邻tab切换
    function tabChange(val) {
        getnearAreaList1(val)
    }
    // 设置单双向取消相邻提交按钮
    function settingnearClick(status, row) {
        let arr = []
        if (row == 'mul') {
            if (state.nearrecords.length == 0) {
                proxy.$modal.msgSuccess('请先勾选所要设置的数据!');
            } else {

                if (status) {
                    state.nearrecords.forEach(item => {
                        arr.push({
                            areaId: state.nearId,
                            nearAreaId: item.id, //nearAreaId
                            status: status
                        })
                    })
                    axios.post(state.settingAreaUrl, arr).then(res => {
                        proxy.$modal.msgSuccess(res.msg);
                        getnearAreaList1(state.nearAreatabName)
                    })
                } else {
                    state.nearrecords.forEach(item => {
                        arr.push({
                            areaId: state.nearId,
                            nearAreaId: item.nearAreaId, //nearAreaId
                            status: status
                        })
                    })
                    axios.post('/area/near/cancel', arr).then(res => {
                        proxy.$modal.msgSuccess(res.msg);
                        getnearAreaList1(state.nearAreatabName)
                    })
                }
            }
        } else {
            if (status) {
                axios.post(state.settingAreaUrl, [{
                    areaId: state.nearId,
                    nearAreaId: row.id,
                    status: status
                }]).then(res => {
                    proxy.$modal.msgSuccess(res.msg);
                    getnearAreaList1(state.nearAreatabName)
                })
            } else {
                axios.post('/area/near/cancel', [{
                    areaId: state.nearId,
                    nearAreaId: row.nearAreaId,
                    status: status
                }]).then(res => {
                    proxy.$modal.msgSuccess(res.msg);
                    getnearAreaList1(state.nearAreatabName)
                })
            }
        }

    }
    // 相邻操作表单复选
    function checkchange(e) {
        state.nearrecords = e.records
    }
    // 切换列表-多维下拉选
    function tabChangeSel(val) {
        state.tabName = val
        if (val == 2) {
            myFn()
        }
    }
    // 递归导图
    const recursionTreeData = (treeData) => {
        let nodeData = [];
        treeData.forEach((item) => {
            if (item.childList) {
                item.children = recursionTreeData(item.childList);
            }
            item.id = item.id,
                item.topic = CreateDom.getModelCardDom({
                    bgc: '#0FA984',
                    modelTitle: item.areaName,
                    modelType: item.id,
                    level: 1,
                    modelWeight: 1,
                    nearAreaInfoNum: item.nearAreaInfoNum,
                    personalInfoNum: item.personalInfoNum,
                    stationInfoNum: item.stationInfoNum,
                    isHighLight: item.isHighLight ? 'model-edit-card active' : 'model-edit-card',
                    elmenu: ''
                })

            function handleClick() {
                console.log('Button was clicked!')
            }

            item.direction = 'right', // 可选  节点的方向  此数据仅在第一层节点上有效，目前仅支持 left 和 right 两种，默认为 right
                item.expanded = true, //  [可选] 该节点是否是展开状态，默认为 true
                item.level = 1,
                item.type = item.id,
                item.title = item.areaName,
                item.parentAreaId = item.parentAreaId
            nodeData.push(item);
        });
        return nodeData;
    };
    // 树形转化成一维
    function flattenTree(tree) {
        let result = [];
        tree.forEach(node => {
            result.push(node);
            if (node.children) {
                result = result.concat(flattenTree(node.children));
            }
        });
        return result;
    }

    function toTree(tarArray) {
        var obj = {}
        tarArray.map((item, index) => {
            obj[item.id] = item
        })
        var newArr = [];
        for (var i = 0; i < tarArray.length; i++) {
            var item = tarArray[i]
            var parent = obj[item.parentAreaId]
            if (parent) {
                if (parent.children) {
                    parent.children.push(item)
                } else {
                    parent.children = []
                    parent.children.push(item)
                }
            } else {
                newArr.push(item)
            }
        }
        return newArr
    }

    function getdaotuList(val) {
        let url = '/area/info/areaTree'
        jm = new JsMind({
            container: jsmindContainer.value, //渲染的体
            editable: false, //是否可以编辑
            theme: "red", //主题色
            enable_drag_and_drop: false, // 禁用节点的拖拽（包括折叠功能）
            // support_html : true,    // 是否支持节点里的HTML元素，如数据中topic 的html属性
            theme: '', // [可选] 主题
            support_html: true,
            mode: 'full', // 显示模式
            view: {
                line_style: "curved", /// 思维导图线条的样式，直线(straight)或者曲线(curved)
                engine: 'canvas', // 思维导图各节点之间线条的绘制引擎
                hmargin: 60, // 思维导图距容器外框的最小水平距离
                vmargin: 20, // 思维导图距容器外框的最小垂直距离
                line_width: 1, // 思维导图线条的粗细
                line_color: 'rgba(217, 217, 217, 1)', // 思维导图线条的颜色
                draggable: true, // 当容器不能完全容纳思维导图时，是否允许拖动画布代替鼠标滚动
                hide_scrollbars_when_draggable: true, // 当设置 draggable = true 时，是否隐藏滚动条.
                zoom: { // 配置缩放
                    min: 0.1, // 最小的缩放比例
                    max: 2.1, // 最大的缩放比例
                    step: 0.1, // 缩放比例间隔
                },
            },
            layout: {
                hspace: 60, // 节点之间的水平间距
                vspace: 20, // 节点之间的垂直间距
                pspace: 0 // 节点与连接线之间的水平间距（用于容纳节点收缩/展开控制器）
            },
            shortcut: {
                enable: false // 是否启用快捷键 默认为true
            },
            menuOpts: {
                showMenu: true,
                injectionList: [{
                        target: 'addBrother',
                        text: '添加同级卡片',
                        callback: function (node) {
                            console.log(node);
                        }
                    },
                    {
                        target: 'delCard',
                        text: '删除卡片',
                        callback: function (node) {
                            console.log(node);
                        }
                    }
                ]
            },
            isShow: true,
            default_event_handle: {
                select_node: (node) => {
                    console.log("Selected node:", node);
                },
            },
        });
        if (val) {
            url = '/area/info/areaTree/' + val
        }
        axios.post(url).then(res => {
            let nodeList = recursionTreeData(res.data); // res.data为tree[]
            resultDatatree.value = nodeList
            if (res.code == 200) {
                const mind = {
                    meta: {
                        name: '建模导图',
                        author: 'ck',
                        version: '0.2'
                    },
                    // 数据格式声明
                    format: 'node_tree',
                    // 数据内容
                    data: {
                        id: 'root',
                        topic: CreateDom.getModelRootDom('this.rootModel'),
                        // direction: 'right',
                        // expanded: false,
                        children: CreateDom.getInitData(resultDatatree.value)
                    }
                }
                nextTick(() => {
                    jm.show(mind);
                })
            }
        })
    }
    onMounted(() => {
        if (jsmindContainer.value) {
            getdaotuList(store.isHighLightid)
            // Define the mind map data
            // Show the mind map
            // 通过原生 DOM 事件捕捉节点点击事件 
            jsmindContainer.value.addEventListener("click", (event) => {
                state.fromtree = true
                const target = event.target;
                const nodeId = target.getAttribute("@click");
                const nodeId1 = target.getAttribute("class");
                if (nodeId == 'addBrother()') {
                    let node = jm.get_selected_node()
                    recursionFun1(node)
                    state.modalTitle = '新增区域'
                    state.addModal = true
                    state.editId = undefined
                    state.formData = {}
                    state.locations = []
                    if (state.formData.parentAreaId == 0) {
                        state.formData.parentAreaId = null
                        state.formData.rootId = null
                    } else {
                        state.formData.parentAreaId = node.id
                        let arr = findParentArr(state.formData.parentAreaId, state.searchTreeList)
                        filtername.value = arr
                    }
                } else if (nodeId == 'editChild()') {
                    let node = jm.get_selected_node()
                    recursionFun1(jm.get_selected_node())
                    state.modalTitle = '编辑区域'
                    state.addModal = true
                    axios.post(state.options.descUrl, {
                        id: node.id
                    }).then(res => {
                        if (res.code == 200) {
                            state.formData = res.data
                            state.locations = res.data.locations
                            state.editId = res.data.id
                            // state.formData.areaTypeId = Number(state.formData.areaTypeId)
                            if (state.formData.parentAreaId == 0) {
                                console.log(state.formData, 'state.formData');
                                state.formData.parentAreaId = null
                                state.formData.rootId = null
                            } else {
                                // state.formData.parentAreaId = node.id
                                // state.formData.parentAreaId = node.id
                                let arr = findParentArr(state.formData.parentAreaId, state
                                    .searchTreeList)
                                filtername.value = arr.reverse()
                            }
                        }
                    })
                } else if (nodeId == 'delCard()') {
                    let node = jm.get_selected_node()
                    axios.post(state.options.delUrl, [node.id]).then(res => {
                        if (res.code == 200) {
                            proxy.$modal.msgSuccess(res.msg);
                            store.records = []
                            jm.remove_node(node.id)
                            myFn()
                        }
                    })
                } else
                if (nodeId1 == 'hover') {
                    let node = jm.get_selected_node()
                    state.drawerShow = true
                    state.nearId = node.id
                    getChildAreaList()
                    getnearAreaList1('已设置相邻')
                    getsearchChildStation()
                    axios.post(state.options.descUrl, {
                        id: node.id
                    }).then(res => {
                        if (res.code == 200) {
                            state.formData = res.data
                        }
                    })
                } else {
                    let node = jm.get_selected_node()
                    if (node != null) {
                        store.isHighLightid = node.id
                        myFn()
                    }
                }
            });
        } else {
            console.error("jsmindContainer is null"); // Log an error if jsmindContainer is null
        }
    });
    // 递归函数
    const recursionFun1 = (node) => {
        if (!node.parent) {
            node.gaoliang = 'model-edit-card'
            return;
        } else {
            filtername1.value.unshift(node.parent.id)
            node.parent.gaoliang = 'model-edit-card active'
            recursionFun1(node.parent)
        }
    }
    // 多维导图
    // 节点点击事件处理函数
    function daotuAddClick() {
        state.modalTitle = '新增区域'
        state.addModal = true
        state.formData = {}
        state.formData.parentAreaId = null
        state.locations = []
        state.editId = undefined
    }

    function handleClose() {
        getnearAreaList1('已设置相邻')
        state.drawerNearShow = false
    }
</script>
<style lang="scss" scoped>
    :deep(.sel .el-input .el-input__wrapper) {
        box-shadow: none !important;
        background: transparent;
    }

    .pagestyle {
        background-color: #fff;

    }

    ::v-deep .allbk {
        .table_box {
            height: calc(100vh - 194px) !important;

            &.w100 {
                .hhhhh {
                    height: calc(100vh - 194px) !important;
                }
            }
        }
    }

    ::v-deep .el-drawer .table_box .fsc {
        display: none;
    }
</style>
<style lang="scss">
    #jsmind_container {
        width: 100%;
        height: 100vh;
    }

    /* Optional styles */
    /* 隐藏所有节点的折叠图标 */
    jmexpander {
        display: none !important;
    }

    jmnode {
        padding: 0;
        border: 1px solid rgba(238, 238, 238, 1);
        box-shadow: none;
        border-radius: 6px;

        &:hover {
            box-shadow: none;
            background-color: rgba(0, 186, 173, 0.14);
            color: #333;
            border: 2px solid rgba(0, 186, 173, 1);
        }
    }

    jmnode.selected {
        background-color: #fff;
        box-shadow: none;
        color: #333;
    }

    .model-edit-card {
        font-size: 14px;

        &.active {
            box-shadow: none;
            background-color: rgba(0, 186, 173, 0.14);
            color: #333;
            border: 2px solid rgba(0, 186, 173, 1);
        }

        .model-title-p {
            font-weight: 700;
            padding: 0 10px 0 30px;
            background-image: url('@/assets/images/dao.png');
            background-repeat: no-repeat;
            background-position: 10px;
        }

        .model-name-info {
            .btn {
                width: 34%;
                display: block;
                padding: 10px 30px;
                color: rgba(62, 70, 79, 0.8);
                border: 1px solid rgba(238, 238, 238, 1);
                cursor: pointer;
            }

            p {
                margin: 0 15px;
                padding: 5px 0;
                color: rgba(53, 140, 240, 1);

                &.p {
                    color: rgba(62, 70, 79, 0.6);

                }
            }

            display: flex;
            justify-content: space-between;
            text-align: center;
        }

    }
</style>